import argparse

def main(dml_file, ASN, router_id, interfaces):
    interfaces.sort()
    lines = []
    with open(dml_file, 'r') as dml:
        AS_line = -1
        lines = dml.readlines()
        for i in range(len(lines)):
            if lines[i].strip().endswith('Net [id {0}'.format(ASN)) > 0:
                AS_line = i
                break
        if AS_line < 0:
            raise RuntimeError("AS {0} isn't defined!".format(ASN))
        AS_line += 1
        router_line = -1

        while not lines[AS_line].strip().startswith('host'):
            if lines[AS_line].find('router') > 0 and lines[AS_line].find('id') > 0 and lines[AS_line].find('{0}'.format(router_id)) > 0:
                router_line = AS_line + 1
                break
            AS_line += 1
        if router_line < 0:
            raise RuntimeError("router {0} isn't defined!".format(router_id))

        while (not lines[router_line].strip().startswith('graph')) and len(interfaces) > 0:
            isInterface = lines[router_line].find('interface  [id {0}'.format(interfaces[0])) > 0
            if isInterface:
                left_bracket = lines[router_line].index('[')
                lines[router_line] = lines[router_line][:left_bracket + 1] + '''tcpdump "''' + '{0}_{1}.dmp' .format(ASN, interfaces[0])+'''" ''' + lines[router_line][left_bracket + 1:]
                del interfaces[0]
            router_line += 1

    
    if len(interfaces) > 0:
        raise RuntimeError("Interfaces {0} aren't marked!".format(interfaces))
    with open(dml_file, 'w') as dml:
        dml.writelines(lines)

if (__name__ == "__main__"):
    parser = argparse.ArgumentParser()
    parser.add_argument('dml_file',)
    parser.add_argument('ASN',)
    parser.add_argument('router_id',)
    parser.add_argument('interfaces', nargs='+', type=int)
    args = parser.parse_args()
    main(**args.__dict__)